package com.odontosis.relatorio.conveniopolicia;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
import com.odontosis.entidade.Mes;
import com.odontosis.entidade.Procedimento;
import com.odontosis.entidade.ServicoConveniado;
import com.odontosis.ioc.ContainerIoc;
import com.odontosis.rel.Relatorio;
import com.odontosis.rel.RelatorioUtil;
import com.odontosis.service.ServicoConveniadoService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisAction;

public class AcaoRelatorioPoliciaPagamento extends OdontosisAction<ServicoConveniadoService> {
	
	/**
	 * Mtodo principal da ao. 
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormRelatorioPoliciaPagamento formRelatorio = (FormRelatorioPoliciaPagamento) actionForm;

		return super.execute(mapping, actionForm, request, response);
	}
	
	public ActionForward vizualizar(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormRelatorioPoliciaPagamento formRelatorio = (FormRelatorioPoliciaPagamento) actionForm;
		SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
		Calendar inicio = Calendar.getInstance();
		inicio.setTime(formato.parse(formRelatorio.getDataInicio()));
		inicio.set(Calendar.HOUR, 0);
		inicio.set(Calendar.MINUTE, 0);
		inicio.set(Calendar.SECOND, 0);
		
		Calendar fim = Calendar.getInstance();
		fim.setTime(formato.parse(formRelatorio.getDataFim()));
		fim.set(Calendar.HOUR, 23);
		fim.set(Calendar.MINUTE, 59);
		fim.set(Calendar.SECOND, 59);
		
		gerarRelatorio(inicio.getTime(), fim.getTime() , formRelatorio.getCodigoProcedimento(), response);
		
		return null;
	}
	
	private void gerarCabecalho(Document documento, Table tabela) throws Exception{
		documento.newPage();
		String credenciado = ContainerIoc.getReciboService().buscarDentista();
		String clinica = ContainerIoc.getReciboService().buscarClinica();
		String cpf = ContainerIoc.getReciboService().buscarCpf();
		String cnpj = ContainerIoc.getReciboService().buscarCnpj();
		float [] tamanhos = {1};
		Table table = criarObjetoTabela(1,tamanhos);
		String tituloTopo = "REMESSA DE CONTAS/GUIAS PARA PROCESSAMENTO NA DIVISÃO DE PROCESSAMENTO DE CONTA DE SÚDE -DPCS, DO INSTITUTO DE PREVIDÊNCIA DOS SERVIDORES MILITARES DO ESTADO DE MINAS GERAIS - IPSM";
		table.addCell(new Cell(new Phrase(tituloTopo, RelatorioUtil.fonteTitulo)));
		documento.add(table);
		
		documento.add(new Paragraph(""));
		
		float []tamanhos2 = {1.3f ,1};
		table = criarObjetoTabela(2, tamanhos2);
		table.addCell(new Cell(new Phrase("Nome do Credenciado: " + credenciado +"\n" + clinica,RelatorioUtil.fontItem)));
		table.addCell(new Cell(new Phrase("CNPJ: " + cnpj +"\nCPF: "+ cpf ,RelatorioUtil.fontItem)));
		documento.add(table);
		documento.add(new Paragraph(""));
	
		
	}
	
	
	public void gerarRelatorio(Date inicio, Date fim, String codigoProcedimento, HttpServletResponse response){
		try{
			//fontes
			Font fontItem = new Font(Font.HELVETICA, 10, Font.NORMAL);
	        Font fontTotal = new Font(Font.HELVETICA, 10, Font.BOLD);
	        Font fonteTitulo = new Font(Font.HELVETICA, 11, Font.BOLD);
	        Font fonteCabecalho = new Font(Font.HELVETICA, 13, Font.BOLD);
	        
			//inicializa documento
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Document document = new Document();
			PdfWriter.getInstance(document, baos);
			document.open();
			
			Collection<ServicoConveniado> resultado = service.pesquisarPorDataECodigo(inicio, fim, codigoProcedimento);
			
			//define o titulo
			SimpleDateFormat formata = new SimpleDateFormat("dd/MM/yyyy");
			String dataInicio = formata.format(inicio.getTime());
			String dataFim = formata.format(fim.getTime());
			
//			String periodo =  dataInicio + " até "+ dataFim;
//			Paragraph paragrafoTitulo = new Paragraph(new Phrase("Relatório dos Conveniados à Polícia Militar\n  "+periodo, fonteCabecalho));
//            paragrafoTitulo.setAlignment(1);
//            document.add(paragrafoTitulo);
			
			float [] tamanhos3 = {1,0.8f,4,1};
			Table table = criarObjetoTabela(4, tamanhos3);
			
			
			double total = 0.0;
			int i = 0;
			for (ServicoConveniado servico : resultado) {
				if(i == 0){
					gerarCabecalho(document,table);
					
					//float [] tamanhos3 = {1,0.8f,4,1};
					table = criarObjetoTabela(4, tamanhos3); 
					
					Cell p1 = new Cell(new Phrase("Período", RelatorioUtil.fonteCabecalhoNormal));
					p1.setColspan(2);
					table.addCell(p1);
					
					Cell p2 = new Cell(new Phrase("Início: " + dataInicio +"\t\t\tFim: " + dataFim , RelatorioUtil.fonteCabecalhoNormal));
					p2.setColspan(2);
					table.addCell(p2);
					
					Cell t1 = new Cell(new Phrase("N. Conta", RelatorioUtil.fonteCabecalho));
					t1.setBackgroundColor(new Color(236, 235, 234));    
					table.addCell(t1);
					
					Cell t2 = new Cell(new Phrase("Perícia", RelatorioUtil.fonteCabecalho));
					t2.setBackgroundColor(new Color(236, 235, 234));
					table.addCell(t2);
					
					Cell t3 = new Cell(new Phrase("Beneficiário", RelatorioUtil.fonteCabecalho));
					t3.setBackgroundColor(new Color(236, 235, 234));
					table.addCell(t3);
					
					Cell t5 = new Cell(new Phrase("Valor", RelatorioUtil.fonteCabecalho));
					t5.setBackgroundColor(new Color(236, 235, 234));
					table.addCell(t5);
				}
				
				Cell conta = new Cell(new Phrase(servico.getFiod() , fontItem));
				table.addCell(conta);
				
				SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
				String dataPericia = servico.getDataPericia() != null ? format.format(servico.getDataPericia()) : null;
				Cell celData = new Cell(new Phrase(dataPericia,fontItem));
				table.addCell(celData);
				
				Cell paciente = new Cell(new Phrase(servico.getPaciente().getNome(), fontItem));
				table.addCell(paciente);
				
				Cell valor = new Cell(new Phrase(StringUtilsOdontosis.formatarDouble(servico.getValor()), fontItem));
				table.addCell(valor);
				total += servico.getValor();
				
				i++;
				if(i == 25){
					totalizar(fontTotal, table, total);
					document.add(table);
					inserirRodaPe(document);
					total = 0;
					i = 0;
				}
			}
			
			if(total > 0){
				totalizar(fontTotal, table, total);
				document.add(table);
				inserirRodaPe( document);
				//document.newPage();
			}
			
			if(resultado.size()  == 0 ) {
				totalizar(fontTotal, table, total);
				document.add(table);
				inserirRodaPe(document);
			}
			
			
			document.close();
			response.setContentType("application/pdf");
			response.setContentLength(baos.size());
			ServletOutputStream out = response.getOutputStream();
			baos.writeTo(out);
			out.flush();
			
		
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void inserirRodaPe(Document documento) throws Exception{
		documento.add(new Paragraph("\n"));
		documento.add(new Paragraph(new Phrase("Belo Horizonte-MG____de______________________________de___________",RelatorioUtil.fontTotal)));
		documento.add(new Paragraph(""));
		documento.add(new Paragraph(new Phrase("CARIMBO E ASSINATURA DO CONTRATADO",RelatorioUtil.fonteRodape)));
		documento.add(new Paragraph(""));
		documento.add(new Paragraph(new Phrase("PROTOCOLO DE ENTRADA Nº____________________/IPSM, DE ___/___/______",RelatorioUtil.fonteRodape)));
		documento.add(new Paragraph(""));
		documento.add(new Paragraph(new Phrase("________________________________________",RelatorioUtil.fonteRodape)));
		documento.add(new Paragraph(new Phrase("ASSINATURA DE RECEPCIONISTA DO IPSM",RelatorioUtil.fonteRodape)));

	}

	private void totalizar(Font fontTotal, Table table, double total)
			throws BadElementException {
		Cell rodape = new Cell(new Phrase("Total"));
		rodape.setColspan(3);
		rodape.setBackgroundColor(new Color(236, 235, 234));    
		table.addCell(rodape);
		
		Cell totaliza = new Cell(new Phrase(StringUtilsOdontosis.formatarDouble(total),fontTotal));
		totaliza.setBackgroundColor(new Color(236, 235, 234));    
		table.addCell(totaliza);
	}
	
	
	private Table criarObjetoTabela(int numColunas, float[] headerWidths) {
	        try {
	            Table aTable = new Table(numColunas);

	            aTable.setPadding(1);
	            aTable.setSpacing(0);

	            aTable.setWidths(headerWidths);

	            aTable.widthPercentage();
	            aTable.setWidth(100);
	            aTable.setBorder(0);

	            aTable.setSpaceBetweenCells(0);

	            aTable.setDefaultCellBorderWidth(0);
	            aTable.setBorder(0);

	            return aTable;
	        } catch (BadElementException e) {
	            throw new RuntimeException("Erro definindo largura do cabeçalho", e);
	        }
	    }

}
